import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import 'package:markdown/markdown.dart' as md show ExtensionSet;
import 'package:html2md/html2md.dart' as html2md;

import '../api/api.dart';
import '../constants.dart';
import '../locator.dart';
import '../src/generated/models/article.pb.dart';
import '../tools/date_format.dart';
import '../tools/string.dart';
import '../tools/build.dart';
import '../routes.dart';
import './components/layout/footer.dart';
import '../tools/check.dart';

class ArticleScreenArgs {
  final int id;

  ArticleScreenArgs(this.id);
}

class ArticleScreen extends StatefulWidget {
  ArticleScreen({super.key});

  @override
  State<ArticleScreen> createState() => _ArticleScreenState();
}

class _ArticleScreenState extends State<ArticleScreen> {
  late ArticleScreenArgs args;
  late ArticleDetail? article;

  Future<ArticleDetail?> getDetail() async {
    article = await locator<Api>().getArticleDetail(args.id);
    if (article != null && CheckTool.isHtmlText(article!.content)) {
      article!.content = html2md.convert(article!.content);
    }

    return article;
  }

  toHome() => Get.toNamed(Routes.home);

  Widget emptyArticle() {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Not Found Page"),
      ),
      body: Center(
        child: Text("找不到文章"),
      ),
    );
  }

  Widget articleContent() {
    return Expanded(
        child: Container(
            constraints: BoxConstraints(
              maxWidth: kMaxWidth * (2 / 3),
            ),
            child: Markdown(
              data: article!.content,
              extensionSet: md.ExtensionSet.commonMark,
              imageBuilder: BuilderTool.markdownImageBuilder,
            )));
  }

  Widget detail(ArticleDetail? article) {
    if (article == null) {
      return emptyArticle();
    }

    return Scaffold(
      appBar: AppBar(
        backgroundColor: kDarkBlackColor,
        title: Text(article.title),
      ),
      body: Column(children: [
        Text(
            "作者：${article.author.isEmpty ? '-' : article.author}　"
            "更新时间：${DateFormatTool.dateWeekDay(article.updatedAt.toInt())}",
            textAlign: TextAlign.center),
        articleContent(),
        Footer(),
      ]),
    );
  }

  @override
  Widget build(BuildContext context) {
    var id = StringTool.parseInt(Get.parameters["id"]);
    if (id == null) {
      Get.toNamed(Routes.notFound);
      return emptyArticle();
    }

    args = ArticleScreenArgs(id);
    return FutureBuilder(
      future: getDetail(),
      builder: BuilderTool.futureBuild<ArticleDetail?>(detail, emptyArticle()),
    );
  }
}
